const mongojs = require('mongojs');
const db = require('../db')

let login = {
    config: {
        description: '登录',
        cors: {
            origin: ['*'],
            additionalHeaders: ['cache-control', 'x-requested-with']
        }
    },
    method: 'post',
    path: '/user/login',
    handler: async (request, h) => {

        let request_body = request.payload

        let userName = request_body.username
        let password = request_body.password

        let stateCode;
        let stateMessage;

        let result = {
            token: '',
            stateCode: '',
            stateMessage: ''
        }

        console.log(`login username: ${userName}, password: ${password}`)
        let promise = function () {
            return new Promise((resolve, reject) => {
                db.user.find((err, docs) => {

                    console.log('用户列表', docs)
                    let user = docs

                    if (err) {
                        console.log("error", err)
                        reject(err)
                    }

                    for (let index = 0; index < user.length; index++) {
                        if (user[index].userName === userName) {
                            if (user[index].password === password) {
                                result.stateCode = '000000';
                                result.stateMessage = 'success';
                                result.token = user[index].cnName + '/' + user[index].userName
                                resolve(result)
                            } else {
                                result.stateCode = '000001'
                                result.stateMessage = 'error password'
                                resolve(result)
                            }
                            break;
                        } else {
                            result.stateCode = '000002'
                            result.stateMessage = '未注册用户'
                            resolve(result)
                        }
                    }
                });
            })
        }
        return await promise();

    }
}

module.exports = login